package main

import (
	"fmt"
	"net/http"

	"06-gin/02-route-group/proto"

	"github.com/gin-gonic/gin"
)

type Good struct {
	ID     int    `uri:"id" binding:"required"`
	Action string `uri:"action" binding:"required"`
}

func loginHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "v1 login ok",
	})
}
func submitHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "v1 submit ok",
	})
}
func goodsDetial(c *gin.Context) {
	// id := c.Param("id")
	// act := c.Param("action")
	var good Good
	if err := c.ShouldBindUri(&good); err != nil {
		fmt.Println(err)
		c.Status(404)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"id":  good.ID,
		"act": good.Action,
	})
}

func main() {
	r := gin.Default()
	v1 := r.Group("/v1")
	{
		v1.POST("/login", loginHandler)
		v1.POST("/submit", submitHandler)
	}

	v2 := r.Group("/goods")
	{
		v2.GET("/:id/:action", goodsDetial)
	}

	r.POST("/post_test", func(ctx *gin.Context) {
		// // 获取form-data
		// a := ctx.PostForm("a")
		// b := ctx.PostForm("b")

		// 获取传递的json数据
		type postTest struct {
			A string `json:"a"`
			B string `json:"b"`
		}
		var pTest postTest
		if err := ctx.ShouldBind(&pTest); err != nil {
			ctx.Status(404)
			return
		}
		ctx.JSON(http.StatusOK, gin.H{
			// "a": a,
			// "b": b,
			"a": pTest.A,
			"b": pTest.B,
		})
	})

	r.GET("/someProtoBuf", func(c *gin.Context) {
		user := &proto.User{
			Name: "Bob",
			Id:   15,
		}
		// 请注意，数据在响应中变为二进制数据
		// 将输出被 protoexample.Test protobuf 序列化了的数据
		c.ProtoBuf(http.StatusOK, user)
	})

	// listen and serve on localhost:8080
	r.Run(":3005")
}
